package org.argus.job.server.system.allocate;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.listener.NamingEvent;
import com.alibaba.nacos.api.naming.pojo.Instance;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * Job Server服务实例信息订阅者
 *
 * @Author 刘文/Cliff Liu
 * @Date 2024/7/24
 */
@Component
@Slf4j
public class JobServerInstanceSubscriber {

    @Autowired
    private NacosDiscoveryProperties nacosDiscoveryProperties;

    @Autowired
    private AppAllocator appAllocator;

    @Value("${spring.application.name}")
    private String applicationName;

    @Value("${spring.cloud.nacos.discovery.group:DEFAULT_GROUP}")
    private String groupName;

    private NamingService namingService;

    @PostConstruct
    public void subscribe() {
        try {
            namingService = NamingFactory.createNamingService(nacosDiscoveryProperties.getNacosProperties());
            namingService.subscribe(applicationName, groupName, event -> {
                if (event instanceof NamingEvent) {
                    appAllocator.allocate(((NamingEvent)event).getInstances(), false);
                }
            });

        } catch (NacosException e) {
            log.error("Subscribe service instance", e);
        }
    }

    public List<Instance> getAllInstances() throws NacosException {
        return namingService.getAllInstances(applicationName, groupName);
    }
}
